﻿using System.Text.RegularExpressions;
using System.Web.Mvc;
using EPiServer.Common;
using EPiServer.Common.Comments;
using EPiServer.Community.Blog;
using JoelAbrahamsson.BlogExtensions;
using JoelAbrahamsson.Web.ExtensionMethods;

namespace JoelAbrahamsson.Web.ModelBinders
{
    public class CommentModelBinder : IModelBinder
    {
        private ExtendedBlogHandlerFacade BlogHandlerFacade { get; set; }

        public CommentModelBinder(ExtendedBlogHandlerFacade blogHandlerFacade)
        {
            BlogHandlerFacade = blogHandlerFacade;
        }
        
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Comment comment = bindingContext.Model as Comment;
            
            if (comment == null)
            {
                Entry entry = BlogHandlerFacade.GetEntryBySlug(GetValue<string>(bindingContext, "slug"));
                if (entry == null)
                    bindingContext.ModelState.AddModelError("Entry", "Unable to bind entry");
                
                string commentContent = GetValue<string>(bindingContext, "comment");
                if (string.IsNullOrEmpty(commentContent))
                    bindingContext.ModelState.AddModelError("comment", "No comment");

                if(!bindingContext.ModelState.IsValid)
                    return null;

                IAuthor author = new GuestAuthor("temp", "temp", "temp");
                Comment newComment = new Comment(entry, commentContent, author);
                newComment.SetAuthorIP(controllerContext.HttpContext.Request.ServerVariables["REMOTE_ADDR"]);
                comment = newComment;
            }

            return comment;
        }

        private T GetValue<T>(ModelBindingContext bindingContext, string key)
        {
            ValueProviderResult valueResult;
            bindingContext.ValueProvider.TryGetValue(key, out valueResult);
            bindingContext.ModelState.SetModelValue(key, valueResult);
            if(valueResult == null)
                return default(T);

            return (T)valueResult.ConvertTo(typeof(T));
        }
    }
}
